var historyPanel = null;
var realTimePanel = null;
var locationPanel = null;
var reportPanel = null;
var managePanel = null;
var settingPanel = null;
var chartPanel = null;
var interestPanel = null;
var geoPanel = null;
var measurePanel = null;
var isExpanded = false;
var settingWin = null;
var currentMap = null;

function getSpace(num) {
	var s = "&nbsp;";
	for ( var i = 0; i < num; i++) {
		s += "&nbsp;";
	}
	return s;
}

function showPanel(type) {
	switch (type) {
	case 'realtime':
		realTimePanel.expand();
		break;
	case 'settings':
		settingPanel.expand();
		break;
	case 'geo':
		geoPanel.expand();
		break;
	case 'history':
		historyPanel.expand();
		break;
	case 'report':
		reportPanel.expand();
		break;
	case 'map':
		locationPanel.expand();
		break;
	case 'distance':
		measurePanel.expand();
		break;
	case 'chart':
		chartPanel.expand();
		break;
	case 'manage':
		managePanel.expand();
		break;
	}
}

function afterLayoutHandler() {
	Ext.get('locationControl').setStyle("display", '');
	Ext.get('realtimeMapDiv').setStyle("display", '');
	initializeRealtime(geomapCountry);
	currentMap = g_map;
}

Ext
		.onReady(function() {
			var expandedPanel = null;
			var space = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';// &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
			var settingSpace = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			settingSpace = settingSpace + settingSpace + settingSpace;
			settingSpace = "";
			locationPanel = new Ext.Panel({
				title : space + '<img src="images/map2.png"/>&nbsp;&nbsp;'
						+ locationTitle,
				// html: '&lt;empty panel&gt;',
				contentEl : 'locationControl',
				cls : 'empty'// ,
			// headerCfg:{tag: 'div', cls: 'panelHeader',html:''}
			});

			locationPanel.on("expand", function() {
				Ext.get('realtimeMapDiv').setStyle("display", 'none');
				Ext.get('historyMapDiv').setStyle("display", 'none');
				Ext.get('locationMapDiv').setStyle("display", '');
				if (location_map == null) {
					initializeLocationMap(geomapCountry);
				} else {
					location_map.checkResize();
					if (gps_map && gps_map[g_seluin] && gps_map[g_seluin].lat) {
						var d = new GPS_LatLng(
								parseFloat(gps_map[g_seluin].lat),
								parseFloat(gps_map[g_seluin].lng));
						location_map.panTo(d);
						location_map.setZoom(focusLevel);
						setLocationLabelForTracker(gps_map[g_seluin].lat,
								gps_map[g_seluin].lng);
					}
				}
				expandedPanel = locationPanel;
				currentMap = location_map;
			});

			Ext.get('realtimePanel').setStyle('display', '');
			realTimePanel = new Ext.Panel({
				title : space + '<img src="images/realtime2.png"/>&nbsp;&nbsp;'
						+ realTimeTitle,
				contentEl : 'realtimePanel',
				cls : 'empty'
			});
			expandedPanel = realTimePanel;
			realTimePanel.on("expand", function(panel) {
				Ext.get('realtimeMapDiv').setStyle("display", '');
				Ext.get('historyMapDiv').setStyle("display", 'none');
				Ext.get('locationMapDiv').setStyle("display", 'none');
				g_map.checkResize();
				expandedPanel = realTimePanel;
				currentMap = g_map;
			});

			realTimePanel.on("bodyresize", function(cmp, aw, ah, rw, rh) {
				if (trackersGrid)
					trackersGrid.setHeight(ah - 56);
				else
					gridHeight = ah - 56;
			});

			settingPanel = new Ext.Panel({
				title : space + '<img src="images/settings2.png"/>&nbsp;&nbsp;'
						+ settingTitle,
				html : '',
				cls : 'empty',
				maskDisabled : false,
				hideCollapseTool : true
			// disabled:true
			});
			settingPanel.on("beforeexpand", function() {
				isExpanded = !expandedPanel.collapsed;
			});

			settingPanel
					.on(
							"expand",
							function() {
								if (isExpanded)
									expandedPanel.expand();
								else
									settingPanel.collapse();
								if (!isSelectTracker()) {
									return;
								}
								createSettingWin();
								settingWin.setWidth(710);
								settingWin.setHeight(390);
								settingWin
										.setTitle(settingTitle
												+ getSpace(82)
												+ gpstracker_map[selectedTrackers[0]].trackerName
												+ ' - '
												+ gpstracker_map[selectedTrackers[0]].userName);
								if (settingWin.getEl().select('iframe').item(0).dom.contentWindow.showWaiting)
									settingWin.getEl().select('iframe').item(0).dom.contentWindow
											.showWaiting();
								if (gpstracker_map[selectedTrackers[0]].carModelId == ''
										|| gpstracker_map[selectedTrackers[0]].carModelId == '7') {// EV02
									settingWin
											.getEl()
											.select('iframe')
											.item(0)
											.set(
													{
														src : './controls/parameters.jsp?trackerId='
																+ gpstracker_map[selectedTrackers[0]].trackerId
													});
								} else if (gpstracker_map[selectedTrackers[0]].carModelId == '10') {// EV06
									settingWin
											.getEl()
											.select('iframe')
											.item(0)
											.set(
													{
														src : './controls/parameters3.jsp?trackerId='
																+ gpstracker_map[selectedTrackers[0]].trackerId
													});
								} else { // 第三方的设置
									settingWin.setHeight(320);
									settingWin
											.getEl()
											.select('iframe')
											.item(0)
											.set(
													{
														src : './controls/parameters2.jsp?trackerId='
																+ gpstracker_map[selectedTrackers[0]].trackerId
													});
								}
								settingWin.show(Ext.getBody());

								// document.getElementById("search_result").contentWindow
							});

			interestPanel = new Ext.Panel({
				title : space + '<img src="images/settings2.png"/>&nbsp;&nbsp;'
						+ interestPoint,
				html : '',
				cls : 'empty',
				maskDisabled : false,
				hideCollapseTool : true
			// disabled:true
			});
			interestPanel.on("beforeexpand", function() {
				isExpanded = !expandedPanel.collapsed;
			});

			interestPanel.on("expand", function() {
				if (isExpanded)
					expandedPanel.expand();
				else
					interestPanel.collapse();
				addPoint();
			});

			geoPanel = new Ext.Panel({
				title : space + '<img src="images/geo2.png"/>&nbsp;&nbsp;'
						+ geoTitle,
				html : '',
				cls : 'empty',
				collapsible : false,
				hideCollapseTool : true
			});

			geoPanel.on("beforeexpand", function() {
				isExpanded = !expandedPanel.collapsed;
			});

			geoPanel
					.on(
							"expand",
							function() {
								if (isExpanded)
									expandedPanel.expand();
								else
									geoPanel.collapse();
								if (!isSelectTracker()) {
									return;
								}
								createSettingWin();
								settingWin.setWidth(750);
								settingWin
										.setTitle(geoTitle
												+ getSpace(83)
												+ gpstracker_map[selectedTrackers[0]].trackerName
												+ ' - '
												+ gpstracker_map[selectedTrackers[0]].userName);
								if (settingWin.getEl().select('iframe').item(0).dom.contentWindow.showWaiting)
									settingWin.getEl().select('iframe').item(0).dom.contentWindow
											.showWaiting();
								settingWin
										.getEl()
										.select('iframe')
										.item(0)
										.set(
												{
													src : './controls/sysgeofence.jsp?trackerId='
															+ gpstracker_map[selectedTrackers[0]].trackerId
												});
								settingWin.show();
							});

			measurePanel = new Ext.Panel({
				title : space + '<img src="images/distance2.png"/>&nbsp;&nbsp;'
						+ measureTitle,
				html : '',
				cls : 'empty',
				collapsible : false,
				hideCollapseTool : true
			});

			measurePanel.on("beforeexpand", function() {
				isExpanded = !expandedPanel.collapsed;
			});
			measurePanel.on("expand", function() {
				if (isExpanded)
					expandedPanel.expand();
				else
					measurePanel.collapse();
				beginMeasure();
			});

			Ext.get('historyPanel').setStyle('display', '');
			historyPanel = new Ext.Panel({
				title : space + '<img src="images/history2.png"/>&nbsp;&nbsp;'
						+ historyTitle,
				// html: '&lt;empty panel&gt;',
				contentEl : 'historyPanel',
				cls : 'empty'
			});
			historyPanel.on("beforeexpand", function() {
				isExpanded = !expandedPanel.collapsed;
			});
			historyPanel.on("expand", function() {
				if (!isSelectTracker()) {
					if (isExpanded)
						expandedPanel.expand();
					else
						historyPanel.collapse();
					return;
				}

				Ext.get('realtimeMapDiv').setStyle("display", 'none');
				Ext.get('historyMapDiv').setStyle("display", '');
				Ext.get('locationMapDiv').setStyle("display", 'none');
				if (history_map == null) {
					initHistoryMap(geomapCountry);
				} else {
					history_map.checkResize();
					if (gps_map && gps_map[g_seluin] && gps_map[g_seluin].lat) {
						var d = new GPS_LatLng(
								parseFloat(gps_map[g_seluin].lat),
								parseFloat(gps_map[g_seluin].lng));
						history_map.panTo(d);
						history_map.setZoom(focusLevel);
					}
				}
				expandedPanel = historyPanel;
				currentMap = history_map;
			});

			historyPanel.on("bodyresize", function(cmp, aw, ah, rw, rh) {
				// console.log(ah);
				if (ah == undefined)
					ah = cmp.getHeight();
				if (ah < 120) {
					return;
				}
				Ext.get('search_result').setStyle('height', (ah - 135) + 'px');
			});

			reportPanel = new Ext.Panel({
				title : space + '<img src="images/report2.png"/>&nbsp;&nbsp;'
						+ reportTitle,
				// html: '&lt;empty panel&gt;',
				contentEl : 'reportPanel',
				cls : 'empty'
			});

			managePanel = new Ext.Panel({
				title : space + '<img src="images/manage2.png"/>&nbsp;&nbsp;'
						+ mamaneTitle,
				// html: '&lt;empty panel&gt;',
				contentEl : 'manageMenu',
				cls : 'empty'
			});

			chartPanel = new Ext.Panel(
					{
						title : space
								+ '<img src="images/chart-search-icon.png"/>&nbsp;&nbsp;'
								+ chartTitle,
						html : '',
						cls : 'empty',
						collapsible : false,
						hideCollapseTool : true
					});
			chartPanel.on("beforeexpand", function() {
				isExpanded = !expandedPanel.collapsed;
			});
			chartPanel
					.on(
							"expand",
							function() {
								if (isExpanded)
									expandedPanel.expand();
								else
									chartPanel.collapse();
								if (!isSelectTracker()) {
									return;
								}
								createSettingWin();
								settingWin.setWidth(750);
								settingWin
										.setTitle(chartTitle
												+ getSpace(83)
												+ gpstracker_map[selectedTrackers[0]].trackerName
												+ ' - '
												+ gpstracker_map[selectedTrackers[0]].userName);
								if (settingWin.getEl().select('iframe').item(0).dom.contentWindow.showWaiting)
									settingWin.getEl().select('iframe').item(0).dom.contentWindow
											.showWaiting();
								settingWin
										.getEl()
										.select('iframe')
										.item(0)
										.set(
												{
													src : './chart.jsp?trackerId='
															+ gpstracker_map[selectedTrackers[0]].trackerId
												});
								settingWin.show();
							});

			reportPanel.on("beforeexpand", function() {
				isExpanded = !expandedPanel.collapsed;
			});
			reportPanel.on("expand", function() {
				if (!isSelectTracker()) {
					if (isExpanded)
						expandedPanel.expand();
					else
						reportPanel.collapse();
					return;
				}

				expandedPanel = reportPanel;
			});

			managePanel.on("expand", function() {
				expandedPanel = managePanel;
			});
			Ext.get('manageMenu').setStyle('display', '');

			var items = [];
			items.push(realTimePanel);
			if (isAdmin)
				items.push(settingPanel);
			items.push(interestPanel);
			if (isAdmin)
				items.push(geoPanel);
			// if(isAdmin)
			// items.push(managePanel);
			items.push(historyPanel);
			items.push(reportPanel);
			items.push(locationPanel);
			items.push(measurePanel);
			items.push(chartPanel);
			items.push(managePanel);

			var accordion = new Ext.Panel({
				region : 'west',
				margins : '0 0 5 5',
				collapsible : true,
				collapseMode : 'mini',
				split : true,
				width : 240,
				layout : 'accordion',
				items : items
			});

			var mapPanel = new Ext.Panel(
					{
						region : 'center',
						html : '<div id="locationMapDiv" style="height:100%;width:100%;margin:0px 0px 0px 0px;display:none">Loading Map...</div>'
								+ '<div id="realtimeMapDiv" style="height:100%;width:100%;margin:0px 0px 0px 0px;display:none">Loading Map...</div>'
								+ '<div id="historyMapDiv" style="height:100%;width:100%;margin:0px 0px 0px 0px;display:none">Loading Map...</div>',
						cls : 'fullstyle'
					});

			var gisinfoPanel = new Ext.Panel({
				region : 'south',
				contentEl : 'gisInfo',
				cls : 'fullstyle',
				style : {
					width : '100%',
					height : '60px'
				}
			});

			var center = new Ext.Panel({
				region : 'center',
				margins : '0 5 5 0',
				// collapsible: true,
				// collapseMode:'mini',
				split : true,
				width : '100%',
				height : '100%',
				layout : 'border',
				defaults : {
					frame : false,
					width : '100%',
					height : '100%'
				},
				layoutConfig : {
					columns : 1,
					rows : 2,
					tableAttrs : {
						style : {
							width : '100%',
							height : '100%'
						}
					}
				},
				items : [ mapPanel, gisinfoPanel ]
			});

			var top_style = 'topbg';
			if (window.location.host.indexOf("gktracking.com") > -1) {
				top_style = 'india_topbg';
			} else if (window.location.host.indexOf("nortesatrastreamento") > -1) {
				top_style = 'brazil_topbg';
			}
			var viewport = new Ext.Viewport(
					{
						layout : 'border',
						items : [
								{
									region : 'north',
									html : '<div class="x-border-layout-ct '
											+ top_style
											+ '"  style="height:100%;text-align:left" ><div style="float:left;width:230px;height:96px;overflow:hidden">&nbsp;</div><div style="float:left;width:720px;">&nbsp;</div>'
											+ Ext.get('loginInfo').dom.innerHTML
											+ '</div>',
									split : false,
									height : 96,
									collapsible : false,
									// collapseMode:'mini',
									border : false,
									margins : '0 0 0 0'
								}, accordion, center ]
					});

			gisinfoPanel.on('move',
					function(adjWidth, adjHeight, rawWidth, rawHeight) {
						setOnlineStatsOriginalPosition(gisinfoPanel
								.getPosition(false));
					});

			setGisInfoGrid();

			afterLayoutHandler();

			// measurePanel.suspendEvents();
			createSearchGrid();

			accordion.on('collapse', function() {
				gis_info_grid.setWidth(center.getWidth());
			});
			accordion.on('expand', function() {
				gis_info_grid.setWidth(center.getWidth());
			});

			createOnlineStats(gisinfoPanel.getPosition(false));

			function isSelectTracker() {
				if (selectedTrackers[0] == null || selectedTrackers[0] == "") {
					// Ext.Msg.alert('', g_str_select_tracker_search);
					Ext.MessageBox.show({
						title : '',
						msg : g_str_select_tracker_search,
						buttons : Ext.MessageBox.OK,
						icon : Ext.MessageBox.WARNING
					});
					return false;
				}
				return true;
			}
			;

			function createSettingWin() {
				if (!settingWin) {
					settingWin = new Ext.Window(
							{
								renderTo : Ext.getBody(),
								layout : 'fit',
								width : 760,
								height : 400,
								closeAction : 'hide',
								plain : false,
								modal : true,
								header : true,
								html : '<iframe width="100%" height="100%" frameborder="0" src=""></iframe>'
							});
				}
			}
			createSettingWin();
			window.setTimeout(function() {
				accordion.doLayout(true);
			}, 5000);

		});

function getCurrentTrackerId() {
	try {
		return gpstracker_map[selectedTrackers[0]].trackerId;
	} catch (e) {
		return "";
	}
}

function modfiyMeileage() {
	Ext.MessageBox
			.prompt('Correct Mileage', 'Please enter a new mileage',
					function(btn, text) {
						if (btn == 'ok') {
							if (text.length < 1) {
								Ext.Msg.alert('Confirm',
										'Mileage can not be empty'); // 这种方式非常常见
								// modfiyMeileage();
							} else {
								if (isNaN(text)) {
									Ext.Msg.alert('Confirm',
											'Please enter the number'); // 这种方式非常常见
									// modfiyMeileage();
								} else {
									update_mileage(text);
								}

							}
						}
					})
}

var gis_info_grid = null;
function setGisInfoGrid() {
	var myData = [ [ '&nbsp;', '&nbsp;', '&nbsp;', '&nbsp;', '&nbsp;',
			'&nbsp;', '&nbsp;', Ext.get('signalInfo').dom.innerHTML, '&nbsp;',
			Ext.get('alarmInfo').dom.innerHTML, '&nbsp;' ] ];
	Ext.get('signalInfo').remove();
	Ext.get('alarmInfo').remove();

	// create the data store
	var store = new Ext.data.ArrayStore({
		fields : [ {
			name : 'Name'
		}, {
			name : 'Date'
		}, {
			name : 'Time'
		}, {
			name : 'Lat'
		}, {
			name : 'Long'
		}, {
			name : 'Speed'
		}, {
			name : 'Address'
		}, {
			name : 'Offline'
		}, {
			name : 'Mileage'
		}, {
			name : 'No Alarm'
		}, {
			name : 'empty'
		} ]
	});
	store.loadData(myData);

	Ext.get('gisInfo').setStyle("display", '');
	// create the Grid
	gis_info_grid = new Ext.grid.GridPanel(
			{
				store : store,
				columns : [
						{
							id : 'Name',
							header : gis_info_name_title,
							renderer : function(val) {
								return '<div id="info_title">' + val + '</div>';
							},
							width : 70,
							dataIndex : 'name',
							menuDisabled : true
						},
						{
							header : gis_info_date_title,
							renderer : function(val) {
								return '<div id="info_date">' + val + '</div>';
							},
							width : 55,
							dataIndex : 'Date',
							menuDisabled : true
						},
						{
							header : gis_info_time_title,
							renderer : function(val) {
								return '<div id="info_time">' + val + '</div>';
							},
							width : 55,
							dataIndex : 'Time',
							menuDisabled : true
						},
						{
							header : gis_info_lat_title,
							renderer : function(val) {
								return '<div id="info_lat">' + val + '</div>';
							},
							width : 60,
							dataIndex : 'Lat',
							menuDisabled : true
						},
						{
							header : gis_info_lng_title,
							renderer : function(val) {
								return '<div id="info_lng">' + val + '</div>';
							},
							width : 60,
							dataIndex : 'Long',
							menuDisabled : true
						},
						{
							header : gis_info_speed_title,
							renderer : function(val) {
								return '<div id="info_speed">' + val + '</div>';
							},
							width : 40,
							dataIndex : 'Speed',
							menuDisabled : true
						},
						{
							header : gis_info_address_title,
							renderer : function(val) {
								return '<div id="info_address">' + val
										+ '</div>';
							},
							width : 140,
							dataIndex : 'Address',
							menuDisabled : true
						},
						{
							header : gis_info_status_title,
							width : 65,
							dataIndex : 'Offline',
							menuDisabled : true
						},
						{
							header : gis_info_acc_status,
							renderer : function(val) {
								return '<div id="info_acc">' + val + '</div>';
							},
							width : 35,
							dataIndex : 'Acc',
							menuDisabled : true
						},
						{
							header : gis_info_door_status,
							renderer : function(val) {
								return '<div id="info_door">' + val + '</div>';
							},
							width : 35,
							dataIndex : 'Door',
							menuDisabled : true
						},
						{
							header : gis_info_mileage_title,
							renderer : function(val) {
								return '<div onclick="modfiyMeileage()" title=" Right to modify Mileage " id="info_mileage">'
										+ val + '</div>';
							},
							width : 80,
							dataIndex : 'Mileage',
							menuDisabled : true
						}, {
							header : gis_info_alarm_title,
							width : 80,
							dataIndex : 'No Alarm',
							menuDisabled : true
						}, {
							header : "",
							width : 15,
							dataIndex : 'empty',
							menuDisabled : true
						} ],
				autoExpandColumn : 'Address',
				height : 60,
				width : '100%',
				disableSelection : true,
				viewConfig : {
					forceFit : true,
					enableRowBody : false,
					showPreview : false,
					autoScroll : false,
					scrollOffset : 2,
					grouping : false,
					getRowClass : function(record, rowIndex, p, store) {
						if (this.showPreview) {
							p.body = '<p>' + record.data.excerpt + '</p>';
							return 'gis-info-data-row';
						}
						return 'gis-info-data-row';
					},
					width : '100%'
				},
				autoFitColumns : true
			});
	gis_info_grid.render('gisInfo');

}